<?php

namespace app\controllers\admin\uni\system;

use app\controllers\admin\base\AdminController;
use app\models\ZRegion as Model;
use function Symfony\Component\String\s;

class AddressController extends AdminController
{
    public function actionMain()
    {
        $list = Model::find()
            ->where(['p_code' => 0])
            ->orderBy(['code' => SORT_ASC])
            ->asArray()
            ->all();

        return $this->success(['list' => $list]);
    }

    public function actionGet()
    {
        $id = $this->post('id');

        $list = Model::find()
            ->where(['p_code' => $id])
            ->orderBy(['code' => SORT_ASC])
            ->asArray()
            ->all();

        return $this->success(['list' => $list]);
    }

    // 保存
    public function actionSave()
    {
        $data = $this->post();
        $mode = Model::findOne(['code' => $data['code']]);
        if ($mode) {
            $mode->name = trim($data['name']);
            $mode->save();
            return $this->success();
        }
    }

    public function actionDelete()
    {
        $data = $this->post();
        $mode = Model::findOne(['code' => $data['code']]);
        if ($mode) {
            $has = Model::find()
                ->where(['p_code' => $data['code']])
                ->one();
            if ($has) {
                return $this->fail('存在子项,不能删除');
            }

            $mode->delete();

            return $this->success();
        }
    }

    public function actionAdd()
    {
        $name = $this->post('name');
        $code = $this->post('code');

        if (!$name) {
            return $this->fail('请填写名称');
        }
        if (!$code) {
            return $this->fail('错误');
        }

        $mode = new Model();
        $mode->name = trim($name);
        $mode->p_code = $code;
        $mode->save();

        return $this->success($mode);
    }

    // 清除地址缓存
    public function actionClear()
    {
        $admin = __DIR__ . '/../../cache';
        $h5 = __DIR__ . '/../../../h5/cache';

        // admin
        if (file_exists($admin . '/province.json')) {
            unlink($admin . '/province.json');
        }
        if (file_exists($admin . '/tree.json')) {
            unlink($admin . '/tree.json');
        }

        // h5
        if (file_exists($h5 . '/tree.json')) {
            unlink($h5 . '/tree.json');
        }

        // 地址识别
        $file = __DIR__ . '/../../../h5/uni/address/data/data.json';
        if (file_exists($file)) {
            unlink($file);
        }

        return $this->success();
    }
}